package org.t411.api.scrapper;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.util.Log;

public class GetMessageIndexTask extends HttpAsyncTask<BasicPaginedResultRequest, List<MessageEntry>> {
	public final static String mailboxUrl = "http://www.t411.me/mailbox/";
	public final static SortRequest DEFAULT_SORT_REQUEST = new SortRequest(SortableField.AGE, SortOrderType.DESC); 
	public final static BasicPaginedResultRequest DEFAULT_REQUEST = new BasicPaginedResultRequest(
			0, DEFAULT_SORT_REQUEST);

	@Override
	protected List<MessageEntry> doInBackground(BasicPaginedResultRequest... arg0) {
		final BasicPaginedResultRequest request = (arg0.length>0)?arg0[0]:DEFAULT_REQUEST;
		final String buildedUrl = buildUrl(request);
		Log.v(this.getClass().getSimpleName(), String.format("begin (%s)", buildedUrl));
		final HttpGet httpRequest = new HttpGet(buildedUrl);
		
		final HttpResponse httpResp = browser.execute(httpRequest);
		final String content = getStringContent(httpResp);
		final Document htmlResponse = Jsoup.parse(content);
		
		HeaderFooterScrapper.readPage(htmlResponse, profile);
		
		final Elements msgRows = htmlResponse.select("table.mailbox.results>tbody>tr");
		final List<MessageEntry> result = new ArrayList<MessageEntry>(msgRows.size());
		for (Element aRow : msgRows) {
			MessageEntry entry = new MessageEntry();
			entry.isRead = ! aRow.classNames().contains("unread");
			entry.id = Integer.parseInt(aRow.child(0).child(0).attr("value"));
			entry.from = aRow.child(1).text();
			entry.subject = aRow.child(2).text();
			entry.date = aRow.child(3).text();
			result.add(entry);
		}
		
		Log.v(this.getClass().getSimpleName(), String.format("finish (%d results)", result.size()));
		return result;
	}
	
	public static String buildUrl(BasicPaginedResultRequest request) {
		final StringBuilder sb = new StringBuilder();
		sb.append(mailboxUrl)
			.append("?order=").append(request.sortRequest.field)
			.append("&type=").append(request.sortRequest.type.id)
			.append("&page=").append(request.targetedPageResult);
		return sb.toString();
	}
	
	public class SortableField {
		public final static String AGE = "added";
		public final static String FROM = "username";
		public final static String SUBJECT = "subject";
	}
}
